package com.springlearn.springbootlearn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springlearn.springbootlearn.common.Result;
import com.springlearn.springbootlearn.entity.SysUser;
import com.springlearn.springbootlearn.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sysuser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/list")
    public Result list() {
        List<SysUser> list = sysUserService.list();
        return Result.success(list);
    }

    @GetMapping("/list02")
    public Result list02(SysUser sysUser) {
        //处理三个查询条件： 用户名  昵称  类型
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(sysUser.getUsername()),"username",sysUser.getUsername());
        queryWrapper.like(StringUtils.hasText(sysUser.getNickname()),"nickname",sysUser.getNickname());
        queryWrapper.eq(StringUtils.hasText(sysUser.getType()),"type",sysUser.getType());

        //添加分页处理
        Page<SysUser> page = Page.of(sysUser.getPageNum(), sysUser.getPageSize());
        List<SysUser> list = sysUserService.list(page, queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("list",list);

        return Result.success(map);
    }

    @PostMapping
    public Result save(@RequestBody SysUser sysUser){
        sysUserService.save(sysUser);
        return Result.success();
    }

    @RequestMapping("/{id}")
    public Result findOne(@PathVariable("id") Integer id){
        SysUser sysUser = sysUserService.getById(id);
        return Result.success(sysUser);
    }

    //Restful风格url的话，修改一般是要发put请求的; 删除是要发送Delete请求的
    @PutMapping
    public Result update(@RequestBody SysUser sysUser){
        sysUserService.updateById(sysUser);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        sysUserService.removeById(id);
        return Result.success();
    }

}
